const BASE_URL = 'http://localhost:354/'

const http = {
  request: (url, option) => {
    return new Promise (async (resolve, reject) => {
      (await fetch(url, option)).then(res => {
        resolve(res)
      }).catch(e => reject(e))
    })
  }
}

const headers = new Headers({
  'accept': 'application/javascript',
  'content-type': 'application/json'
})

const parseParams = params => {
  if (!params || !Object.keys(params).length) return ''
  return `?${Object.keys(params).map(k => `${k}=${params[k]}`).join('&')}`
}

const keys = ['get', 'post', 'put', 'delete']

keys.forEach(key => {
  http[key] = (url, option = {}) => {
    return new Promise ((resolve, reject) => {
      const { params, data, ...rest } = option
      rest.method = key
      rest.headers = headers
      url = '/api/' + url + parseParams(params)
      rest.body = JSON.stringify(data)
      fetch(url, rest).then(res => {
        if (res.ok) {
          resolve(res.json())
        } else {
          reject({
            status: res.status,
            message: res.statusText
          })
        }
      })
    })
  }
})

export default http
